package com.rainman.simpleredis.core.unique_id;

import com.rainman.simpleredis.core.config.SimpleRedisConfig;
import com.rainman.simpleredis.core.scheduled.ScheduledInfo;
import com.rainman.simpleredis.core.scheduled.SimpleScheduled;
import com.rainman.simpleredis.core.scheduled.SimpleScheduledWorkerInterface;

import java.util.Set;

public class SimpleUniqueId {


    private final SimpleRedisConfig simpleRedisConfig;

    private final Long timeSub;

    private final String UniqueIdHead;//RS0.

    ScheduledInfo info=ScheduledInfo.buildDelay(60000L);

    public SimpleUniqueId(SimpleRedisConfig simpleRedisConfig, SimpleScheduled simpleScheduled){

        this.simpleRedisConfig = simpleRedisConfig;

        UniqueIdHead=simpleRedisConfig.getKeyHead()+simpleRedisConfig.getProduct()
                +".SimpleUniqueId:";//RS0.SimpleUniqueId:
        timeSub=System.currentTimeMillis()-simpleRedisConfig.getRedisInterface().curRedisTime();

        simpleScheduled.addWorker(new SimpleScheduledWorkerInterface() {
            @Override
            public void doWork() {


                Set<String> keys = simpleRedisConfig.getRedisInterface().keys(UniqueIdHead + "*");

                Long needDel=(System.currentTimeMillis()-timeSub)/1000-60;

                for(String key:keys){

                    String[] split = key.split(":");

                    Long time=Long.parseLong(split[1]);


                    if(time<needDel){

                        simpleRedisConfig.getRedisInterface().delete(key);
                    }


                }

            }

            @Override
            public String key() {
                return "SimpleUniqueId.ScanData";
            }

            @Override
            public ScheduledInfo info() {
                return info;
            }
        });

    }


    public Long getOne(){

        Long curTime=System.currentTimeMillis()/1000;
        Long realTime=curTime-timeSub/1000;

        Long increment = simpleRedisConfig.getRedisInterface().increment(UniqueIdHead + realTime);

        while (increment>996){

            realTime=getNextTimestamp(curTime)-timeSub/1000;
            increment = simpleRedisConfig.getRedisInterface().increment(UniqueIdHead + realTime);

        }

        return realTime*1000+increment;
    }

    private long getNextTimestamp(long lastTimestamp) {
        long timestamp = System.currentTimeMillis()/1000;
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis()/1000;
        }
        return timestamp;
    }

}
